<template>
  <basic-modal
    title="快捷选项"
    v-bind="$attrs"
    show-confirm
    @confirm="handleConfirm"
    :confirm-loading="confirmLoading"
  >
    <n-form :model="modelForm" ref="formRef">
      <n-form-item label="产品" path="variantId">
        <n-select
          placeholder="输入产品名称搜索"
          v-model:value="modelForm.variantId"
          label-field="name"
          value-field="id"
          :options="variantOpts"
          :loading="searchLoading"
          clearable
          filterable
          remote
          @search="handleChangeVariantName"
        />
      </n-form-item>
      <n-form-item label="排序" path="sort">
        <n-input-number v-model:value="modelForm.sort" class="w-full" />
      </n-form-item>
    </n-form>
  </basic-modal>
</template>
<script setup lang="ts">
import { reactive, ref, useAttrs, watch } from "vue";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";
import { getVariantsList } from "@/api/product/product.api";
import { addVariantQuickItem } from "@/api/variantQuickItem/variantQuickItem.api";
import { IQuickItemModalProps } from "./props";
import { debounce, get } from "lodash-es";

const $attrs = useAttrs();

const props = withDefaults(defineProps<IQuickItemModalProps>(), {
  type: "sales",
  actionType: ActionTypeEnum.ADD,
});

const $emits = defineEmits(["confirm"]);

const confirmLoading = ref<boolean>(false);
const modelForm = reactive({
  id: "",
  variantId: undefined,
  sort: undefined,
});
const searchLoading = ref<boolean>(false);
const variantOpts = ref<any[]>([]);

watch(
  () => $attrs.show,
  (newVal) => {
    if (!newVal) {
      modelForm.id = "";
      modelForm.variantId = undefined;
      modelForm.sort = undefined;
      variantOpts.value = [];
    }
  }
);

const handleChangeVariantName = debounce(async function (variantName: string) {
  searchLoading.value = true;
  try {
    const params = {
      type: props.type,
      page: 1,
      pageSize: 10,
      name: `*${variantName}*`,
    };

    const res = await getVariantsList(params);
    console.log(res);
    variantOpts.value = get(res, "result.records") || [];
  } finally {
    searchLoading.value = false;
  }
}, 200);

const handleConfirm = debounce(function () {
  if (props.actionType === ActionTypeEnum.ADD) {
    handleCreateQuickItem();
  }
}, 200);

const handleCreateQuickItem = async function () {
  confirmLoading.value = true;
  try {
    const params = {
      type: props.type,
      variantId: modelForm.variantId,
      sort: modelForm.sort,
    };
    await addVariantQuickItem(params);
    $emits("confirm");
  } finally {
    confirmLoading.value = false;
  }
};
</script>
